<template>
  <div v-if="modelValue" class="modal-overlay" @click="handleOverlayClick">
    <div class="apple-card modal-dialog detail-dialog" @click.stop>
      <div class="apple-card__header">
        <div class="header-content">
          <h2 class="text-heading">用户详情</h2>
          <p v-if="user" class="text-caption">{{ user.real_name }} ({{ user.username }})</p>
        </div>
        <button 
          class="close-button apple-button apple-button--text"
          @click="handleClose"
        >
          ✕
        </button>
      </div>

      <div class="apple-card__body">
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p class="text-body">加载用户详情...</p>
        </div>

        <div v-else-if="userDetail" class="detail-content">
          <!-- 用户头像和基本信息 -->
          <div class="user-profile">
            <div class="user-avatar-large">
              <img 
                v-if="userDetail.avatar_url" 
                :src="userDetail.avatar_url" 
                :alt="userDetail.real_name"
                class="avatar-image"
              >
              <div v-else class="avatar-placeholder">
                {{ userDetail.real_name?.charAt(0)?.toUpperCase() || '?' }}
              </div>
            </div>
            
            <div class="user-basic-info">
              <h3 class="user-name">{{ userDetail.real_name }}</h3>
              <p class="user-username">@{{ userDetail.username }}</p>
              <div class="user-tags">
                <span 
                  :class="['apple-tag', getStatusTagClass(userDetail.status)]"
                >
                  {{ getStatusText(userDetail.status) }}
                </span>
                <span v-if="userDetail.is_superuser" class="apple-tag apple-tag--warning">
                  超级用户
                </span>
              </div>
            </div>
          </div>

          <!-- 详细信息 -->
          <div class="detail-sections">
            <!-- 联系信息 -->
            <div class="detail-section">
              <h4 class="section-title">联系信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <div class="info-label">邮箱地址</div>
                  <div class="info-value">{{ userDetail.email }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">手机号</div>
                  <div class="info-value">{{ userDetail.phone || '-' }}</div>
                </div>
              </div>
            </div>

            <!-- 组织信息 -->
            <div class="detail-section">
              <h4 class="section-title">组织信息</h4>
              <div class="info-grid">
                <div class="info-item">
                  <div class="info-label">员工编号</div>
                  <div class="info-value">{{ userDetail.employee_id || '-' }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">部门</div>
                  <div class="info-value">{{ userDetail.department || '-' }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">职位</div>
                  <div class="info-value">{{ userDetail.position || '-' }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">直属领导</div>
                  <div class="info-value">{{ getManagerName() || '-' }}</div>
                </div>
              </div>
            </div>

            <!-- 角色和权限 -->
            <div class="detail-section">
              <h4 class="section-title">角色和权限</h4>
              
              <div class="roles-section">
                <div class="subsection-title">已分配角色</div>
                <div v-if="userDetail.roles && userDetail.roles.length > 0" class="roles-list">
                  <div 
                    v-for="role in userDetail.roles" 
                    :key="role.id"
                    class="role-card"
                  >
                    <div class="role-info">
                      <div class="role-name">{{ role.name }}</div>
                      <div class="role-code">{{ role.code }}</div>
                    </div>
                    <div class="role-meta">
                      <div class="role-assigned">分配时间: {{ formatDate(role.assigned_at) }}</div>
                      <div v-if="role.expires_at" class="role-expires">
                        过期时间: {{ formatDate(role.expires_at) }}
                      </div>
                      <span 
                        :class="['apple-tag', role.is_active ? 'apple-tag--success' : 'apple-tag--danger']"
                      >
                        {{ role.is_active ? '激活' : '禁用' }}
                      </span>
                    </div>
                  </div>
                </div>
                <div v-else class="empty-roles">
                  <p class="text-caption">暂未分配任何角色</p>
                </div>
              </div>

              <div class="permissions-section">
                <div class="subsection-title">权限列表</div>
                <div v-if="userDetail.permissions && userDetail.permissions.length > 0" class="permissions-list">
                  <div class="permissions-grid">
                    <span 
                      v-for="permission in userDetail.permissions" 
                      :key="permission"
                      class="apple-tag apple-tag--primary permission-tag"
                    >
                      {{ permission }}
                    </span>
                  </div>
                </div>
                <div v-else class="empty-permissions">
                  <p class="text-caption">暂无权限</p>
                </div>
              </div>
            </div>

            <!-- 账户状态 -->
            <div class="detail-section">
              <h4 class="section-title">账户状态</h4>
              <div class="info-grid">
                <div class="info-item">
                  <div class="info-label">创建时间</div>
                  <div class="info-value">{{ formatDate(userDetail.created_at) }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">最后更新</div>
                  <div class="info-value">{{ formatDate(userDetail.updated_at) }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">最后登录</div>
                  <div class="info-value">
                    {{ userDetail.last_login_at ? formatDate(userDetail.last_login_at) : '从未登录' }}
                  </div>
                </div>
                <div class="info-item">
                  <div class="info-label">登录IP</div>
                  <div class="info-value">{{ userDetail.last_login_ip || '-' }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">登录次数</div>
                  <div class="info-value">{{ userDetail.login_count || 0 }}</div>
                </div>
                <div class="info-item">
                  <div class="info-label">账户状态</div>
                  <div class="info-value">
                    <span :class="['apple-tag', userDetail.is_active ? 'apple-tag--success' : 'apple-tag--danger']">
                      {{ userDetail.is_active ? '启用' : '禁用' }}
                    </span>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="apple-card__footer">
        <button 
          type="button"
          class="apple-button apple-button--secondary"
          @click="handleClose"
        >
          关闭
        </button>
        <button 
          v-if="userDetail && !userDetail.is_superuser"
          type="button"
          class="apple-button apple-button--primary"
          @click="editUser"
        >
          编辑用户
        </button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch } from 'vue'
import { userApi } from '@/api/users'
import type { User } from '@/types/rbac'

// Props
interface Props {
  modelValue: boolean
  user: User | null
}

// Emits
interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'edit', user: User): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 状态
const loading = ref(false)
const userDetail = ref<any>(null)

// 加载用户详情
const loadUserDetail = async () => {
  if (!props.user) return
  
  loading.value = true
  try {
    const response = await userApi.getUserById(props.user.id)
    if (response.success) {
      userDetail.value = response.data
    }
  } catch (error) {
    console.error('加载用户详情失败:', error)
  } finally {
    loading.value = false
  }
}

// 工具函数
const getStatusTagClass = (status: string) => {
  const classes = {
    'active': 'apple-tag--success',
    'inactive': 'apple-tag--warning',
    'suspended': 'apple-tag--danger',
    'locked': 'apple-tag--danger'
  }
  return classes[status as keyof typeof classes] || 'apple-tag'
}

const getStatusText = (status: string) => {
  const texts = {
    'active': '激活',
    'inactive': '未激活',
    'suspended': '暂停',
    'locked': '锁定'
  }
  return texts[status as keyof typeof texts] || status
}

const formatDate = (dateString?: string) => {
  if (!dateString) return '-'
  
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

const getManagerName = () => {
  // TODO: 获取管理者姓名，需要从API返回的数据中获取
  return userDetail.value?.manager_name || null
}

// 事件处理
const handleClose = () => {
  emit('update:modelValue', false)
}

const handleOverlayClick = () => {
  handleClose()
}

const editUser = () => {
  if (userDetail.value) {
    emit('edit', userDetail.value)
    handleClose()
  }
}

// 监听对话框打开和用户变化
watch([() => props.modelValue, () => props.user], ([newValue, newUser]) => {
  if (newValue && newUser) {
    loadUserDetail()
  }
})
</script>

<style scoped>
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: var(--spacing-lg);
}

.detail-dialog {
  width: 100%;
  max-width: 800px;
  max-height: 90vh;
  overflow: hidden;
  animation: modalSlideIn var(--duration-normal) var(--ease-out);
}

@keyframes modalSlideIn {
  from {
    opacity: 0;
    transform: translateY(-20px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

.apple-card__header {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  flex: 1;
}

.header-content .text-caption {
  margin-top: var(--spacing-xs);
  color: var(--text-secondary);
}

.close-button {
  padding: var(--spacing-xs);
  font-size: 18px;
  opacity: 0.6;
}

.close-button:hover {
  opacity: 1;
}

.apple-card__body {
  max-height: 60vh;
  overflow-y: auto;
}

.loading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 300px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid var(--apple-gray-5);
  border-top: 3px solid var(--color-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: var(--spacing-md);
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.user-profile {
  display: flex;
  align-items: center;
  gap: var(--spacing-lg);
  margin-bottom: var(--spacing-xl);
  padding: var(--spacing-lg);
  background-color: var(--bg-secondary);
  border-radius: var(--radius-large);
}

.user-avatar-large {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: var(--shadow-medium);
}

.avatar-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.avatar-placeholder {
  width: 100%;
  height: 100%;
  background-color: var(--color-primary);
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: 600;
}

.user-basic-info {
  flex: 1;
  min-width: 0;
}

.user-name {
  margin: 0 0 var(--spacing-xs) 0;
  color: var(--text-primary);
  font-size: 24px;
  font-weight: 600;
}

.user-username {
  margin: 0 0 var(--spacing-md) 0;
  color: var(--text-secondary);
  font-family: 'SF Mono', Monaco, monospace;
}

.user-tags {
  display: flex;
  gap: var(--spacing-sm);
  flex-wrap: wrap;
}

.detail-sections {
  padding-right: var(--spacing-xs);
}

.detail-section {
  margin-bottom: var(--spacing-xl);
  padding-bottom: var(--spacing-lg);
  border-bottom: 1px solid var(--border-secondary);
}

.detail-section:last-child {
  border-bottom: none;
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 var(--spacing-lg) 0;
  color: var(--color-primary);
  font-size: 16px;
  font-weight: 600;
}

.subsection-title {
  margin: 0 0 var(--spacing-md) 0;
  color: var(--text-primary);
  font-size: 14px;
  font-weight: 500;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: var(--spacing-md);
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-xs);
}

.info-label {
  font-size: 12px;
  color: var(--text-tertiary);
  font-weight: 500;
}

.info-value {
  font-size: 14px;
  color: var(--text-primary);
  word-break: break-word;
}

.roles-section {
  margin-bottom: var(--spacing-lg);
}

.roles-list {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-md);
}

.role-card {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--spacing-md);
  border: 1px solid var(--border-secondary);
  border-radius: var(--radius-medium);
  background-color: var(--bg-secondary);
}

.role-info {
  flex: 1;
}

.role-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: var(--spacing-xs);
}

.role-code {
  font-size: 12px;
  color: var(--text-tertiary);
  font-family: 'SF Mono', Monaco, monospace;
}

.role-meta {
  display: flex;
  flex-direction: column;
  align-items: flex-end;
  gap: var(--spacing-xs);
  font-size: 11px;
  color: var(--text-tertiary);
}

.permissions-section {
  margin-bottom: var(--spacing-lg);
}

.permissions-grid {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-xs);
}

.permission-tag {
  font-size: 11px;
}

.empty-roles,
.empty-permissions {
  padding: var(--spacing-lg);
  text-align: center;
  background-color: var(--bg-secondary);
  border-radius: var(--radius-medium);
  border: 2px dashed var(--border-secondary);
}

.apple-card__footer {
  justify-content: flex-end;
}

@media (max-width: 768px) {
  .modal-overlay {
    padding: var(--spacing-md);
  }
  
  .detail-dialog {
    max-height: 95vh;
  }
  
  .user-profile {
    flex-direction: column;
    text-align: center;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .role-card {
    flex-direction: column;
    align-items: stretch;
    gap: var(--spacing-md);
  }
  
  .role-meta {
    align-items: flex-start;
  }
  
  .apple-card__footer {
    flex-direction: column-reverse;
    gap: var(--spacing-sm);
  }
  
  .apple-card__footer .apple-button {
    width: 100%;
  }
}
</style>